// BOSS选择页面交互功能
$(document).ready(function() {
    // 初始化页面
    initPage();
    
    // 绑定事件监听器
    bindEvents();
});

// 页面初始化
function initPage() {
    // 显示默认的常见难度BOSS
    showDifficulty('common');
    
    // 添加页面加载动画
    $('body').addClass('loaded');
    
    // 初始化BOSS卡片动画
    initBossCardAnimations();
}

// 绑定事件监听器
function bindEvents() {
    // 难度卡片点击事件
    $('.difficulty-card').on('click', function() {
        const difficulty = $(this).data('difficulty');
        selectDifficulty(difficulty);
    });
    
    // BOSS选择按钮点击事件（排除敬请期待的BOSS）
    $('.boss-select-btn').on('click', function() {
        const bossCard = $(this).closest('.boss-card');
        
        // 检查是否是敬请期待的BOSS
        if (bossCard.hasClass('boss-coming-soon')) {
            playSound('disabled');
            return;
        }
        
        const bossId = bossCard.data('boss');
        const bossName = bossCard.find('.boss-name').text();
        selectBoss(bossId, bossName);
    });
    
    // 键盘快捷键
    $(document).on('keydown', function(e) {
        handleKeyboardShortcuts(e);
    });
    
    // 返回按钮点击事件
    $('.btn-outline-light').on('click', function() {
        goBack();
    });
    
    // 帮助按钮点击事件
    $('.btn-outline-warning').on('click', function() {
        showHelp();
    });
}

// 选择难度
function selectDifficulty(difficulty) {
    // 移除所有难度卡片的激活状态
    $('.difficulty-card').removeClass('active');
    
    // 激活当前选择的难度卡片
    $(`.difficulty-card[data-difficulty="${difficulty}"]`).addClass('active');
    
    // 显示对应的BOSS区域
    showDifficulty(difficulty);
    
    // 播放选择音效
    playSound('select');
}

// 显示指定难度的BOSS
function showDifficulty(difficulty) {
    // 隐藏所有BOSS区域
    $('.boss-section').removeClass('active');
    
    // 显示当前难度的BOSS区域
    $(`.boss-section[data-difficulty="${difficulty}"]`).addClass('active');
    
    // 添加动画效果
    animateBossCards();
}

// 初始化BOSS卡片动画
function initBossCardAnimations() {
    // 为每个BOSS卡片添加延迟动画
    $('.boss-card').each(function(index) {
        $(this).css({
            'opacity': '0',
            'transform': 'translateY(30px)'
        });
    });
}

// 动画显示BOSS卡片
function animateBossCards() {
    const activeSection = $('.boss-section.active');
    const bossCards = activeSection.find('.boss-card');
    
    bossCards.each(function(index) {
        const card = $(this);
        setTimeout(function() {
            card.css({
                'opacity': '1',
                'transform': 'translateY(0)',
                'transition': 'all 0.5s ease'
            });
        }, index * 100); // 延迟显示每个卡片
    });
}

// 选择BOSS
function selectBoss(bossId, bossName) {
    // 显示加载状态
    const selectBtn = $(`.boss-card[data-boss="${bossId}"] .boss-select-btn`);
    const originalText = selectBtn.html();
    selectBtn.html('<span class="loading"></span> 加载中...');
    selectBtn.prop('disabled', true);
    
    // 播放选择音效
    playSound('boss-select');
    
    // 显示确认对话框
    showBossConfirmDialog(bossId, bossName, function() {
        // 用户确认选择
        startBossBattle(bossId);
    }, function() {
        // 用户取消选择
        selectBtn.html(originalText);
        selectBtn.prop('disabled', false);
    });
}

// 显示BOSS确认对话框
function showBossConfirmDialog(bossId, bossName, onConfirm, onCancel) {
    // 创建模态框HTML
    const modalHtml = `
        <div class="modal fade" id="bossConfirmModal" tabindex="-1">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content bg-dark text-light">
                    <div class="modal-header border-0">
                        <h5 class="modal-title">
                            <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>
                            确认挑战BOSS
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body text-center">
                        <div class="boss-confirm-avatar mb-3">
                            <i class="bi bi-shield-fill text-danger" style="font-size: 3rem;"></i>
                        </div>
                        <h4 class="text-warning mb-3">${bossName}</h4>
                        <p class="mb-4">你确定要挑战这个强大的BOSS吗？</p>
                        <div class="boss-stats mb-4">
                            <div class="row text-center">
                                <div class="col-4">
                                    <div class="stat">
                                        <span class="stat-label">难度</span>
                                        <span class="stat-value text-warning">${getDifficultyLevel(bossId)}</span>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="stat">
                                        <span class="stat-label">生命值</span>
                                        <span class="stat-value text-danger">${getBossHP(bossId)}</span>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="stat">
                                        <span class="stat-label">攻击力</span>
                                        <span class="stat-value text-info">${getBossAttack(bossId)}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <p class="text-muted small">挑战失败不会影响你的游戏进度，但会消耗一次挑战机会。</p>
                    </div>
                    <div class="modal-footer border-0 justify-content-center">
                        <button type="button" class="btn btn-secondary me-3" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmBattle">
                            <i class="bi bi-sword me-2"></i>开始挑战
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加模态框到页面
    $('body').append(modalHtml);
    
    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('bossConfirmModal'));
    modal.show();
    
    // 绑定确认按钮事件
    $('#confirmBattle').on('click', function() {
        modal.hide();
        setTimeout(function() {
            $('#bossConfirmModal').remove();
            onConfirm();
        }, 300);
    });
    
    // 绑定取消事件
    $('#bossConfirmModal').on('hidden.bs.modal', function() {
        setTimeout(function() {
            $('#bossConfirmModal').remove();
            onCancel();
        }, 300);
    });
}

// 开始BOSS战斗
function startBossBattle(bossId) {
    // 显示加载页面
    showLoadingScreen(`正在加载 ${getBossName(bossId)} 的战斗场景...`);
    
    // 模拟加载过程
    setTimeout(function() {
        // 跳转到BOSS战斗页面
        window.location.href = `boss-game.html?boss=${bossId}`;
    }, 1000);
}

// 键盘快捷键处理
function handleKeyboardShortcuts(e) {
    switch(e.key) {
        case '1':
            e.preventDefault();
            selectDifficulty('common');
            break;
        case '2':
            e.preventDefault();
            selectDifficulty('normal');
            break;
        case '3':
            e.preventDefault();
            selectDifficulty('hard');
            break;
        case '4':
            e.preventDefault();
            selectDifficulty('hell');
            break;
        case 'Escape':
            e.preventDefault();
            goBack();
            break;
        case 'h':
        case 'H':
            e.preventDefault();
            showHelp();
            break;
    }
}

// 返回主页
function goBack() {
    // 添加离开动画
    $('body').addClass('leaving');
    
    setTimeout(function() {
        window.location.href = 'game-home.html';
    }, 500);
}

// 显示帮助信息
function showHelp() {
    const helpHtml = `
        <div class="modal fade" id="helpModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content bg-dark text-light">
                    <div class="modal-header border-0">
                        <h5 class="modal-title">
                            <i class="bi bi-question-circle-fill text-info me-2"></i>
                            BOSS挑战模式帮助
                        </h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6 class="text-warning">难度说明</h6>
                                <ul class="list-unstyled">
                                    <li><span class="text-success">★☆☆☆</span> 常见：适合新手玩家</li>
                                    <li><span class="text-primary">★★☆☆</span> 普通：标准难度</li>
                                    <li><span class="text-warning">★★★☆</span> 困难：高难度挑战</li>
                                    <li><span class="text-danger">★★★★</span> 地狱：极限挑战</li>
                                </ul>
                            </div>
                            <div class="col-md-6">
                                <h6 class="text-warning">快捷键</h6>
                                <ul class="list-unstyled">
                                    <li><kbd>1-4</kbd> 切换难度</li>
                                    <li><kbd>ESC</kbd> 返回主页</li>
                                    <li><kbd>H</kbd> 显示帮助</li>
                                </ul>
                            </div>
                        </div>
                        <hr class="my-4">
                        <h6 class="text-warning">BOSS特性</h6>
                        <p class="small text-muted">每个BOSS都有独特的攻击模式和特殊能力，挑战前请仔细阅读BOSS描述和属性。</p>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('body').append(helpHtml);
    const modal = new bootstrap.Modal(document.getElementById('helpModal'));
    modal.show();
    
    $('#helpModal').on('hidden.bs.modal', function() {
        $(this).remove();
    });
}

// 播放音效
function playSound(type) {
    // 在实际实现中，这里应该播放对应的音效文件
    // 暂时使用控制台日志代替
    console.log(`播放音效: ${type}`);
}

// 显示加载屏幕
function showLoadingScreen(message) {
    const loadingHtml = `
        <div id="loadingScreen" class="loading-screen">
            <div class="loading-content">
                <div class="loading-spinner"></div>
                <p class="loading-message">${message}</p>
            </div>
        </div>
    `;
    
    $('body').append(loadingHtml);
}

// 隐藏加载屏幕
function hideLoadingScreen() {
    $('#loadingScreen').remove();
}

// 显示成功消息
function showSuccessMessage(message) {
    const successHtml = `
        <div class="alert alert-success alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-5" role="alert">
            <i class="bi bi-check-circle-fill me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(successHtml);
    
    // 5秒后自动消失
    setTimeout(function() {
        $('.alert').alert('close');
    }, 5000);
}

// BOSS数据获取函数
function getBossName(bossId) {
    const bossNames = {
        'rock-serpent': '岩石巨蟒',
        'lightning-viper': '闪电蝰蛇',
        'venom-king': '毒液王蛇',
        'frost-serpent': '冰霜巨蟒',
        'flame-demon': '火焰魔蛇',
        'shadow-king': '暗影蛇王',
        'thunder-serpent': '雷霆巨蟒',
        'lava-serpent': '熔岩巨蛇',
        'time-serpent': '时空蛇神',
        'chaos-serpent': '混沌魔蛇',
        'void-devourer': '虚空吞噬者',
        'final-serpent': '终焉之蛇'
    };
    return bossNames[bossId] || '未知BOSS';
}

function getDifficultyLevel(bossId) {
    const difficulties = {
        'rock-serpent': '常见',
        'lightning-viper': '常见',
        'venom-king': '常见',
        'frost-serpent': '普通',
        'flame-demon': '普通',
        'shadow-king': '普通',
        'thunder-serpent': '困难',
        'lava-serpent': '困难',
        'time-serpent': '困难',
        'chaos-serpent': '地狱',
        'void-devourer': '地狱',
        'final-serpent': '地狱'
    };
    return difficulties[bossId] || '未知';
}

function getBossHP(bossId) {
    const hpValues = {
        'rock-serpent': '1000',
        'lightning-viper': '800',
        'venom-king': '900',
        'frost-serpent': '1500',
        'flame-demon': '1400',
        'shadow-king': '1300',
        'thunder-serpent': '2000',
        'lava-serpent': '2200',
        'time-serpent': '1800',
        'chaos-serpent': '3000',
        'void-devourer': '2800',
        'final-serpent': '3500'
    };
    return hpValues[bossId] || '0';
}

function getBossAttack(bossId) {
    const attackValues = {
        'rock-serpent': '20',
        'lightning-viper': '30',
        'venom-king': '25',
        'frost-serpent': '35',
        'flame-demon': '40',
        'shadow-king': '45',
        'thunder-serpent': '50',
        'lava-serpent': '55',
        'time-serpent': '60',
        'chaos-serpent': '70',
        'void-devourer': '75',
        'final-serpent': '80'
    };
    return attackValues[bossId] || '0';
}